<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-lx-cascades"></i>模型数据</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" icon="delete" class="handle-del mr10" @click="dialogAddFormVisible=true">
                    添加模型
                </el-button>
                <el-button type="primary" icon="delete" class="handle-del mr10" @click="delAll">批量删除</el-button>
                <el-select v-model="select_cate" placeholder="筛选类型" class="handle-select mr10">
                    <el-option label="全部" value="all"></el-option>
                    <el-option v-for="(key,value) in typeMap" :label="key" :value="value"></el-option>
                </el-select>
                <el-input v-model="select_word" placeholder="筛选关键词" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="search" @click="search">搜索</el-button>
            </div>
            <el-table :data="data" border class="table" ref="multipleTable" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column align="left" label="模型名称" prop="fileName"></el-table-column>
                <el-table-column
                        :formatter="formatType"
                        label="模型分类"
                        prop="type">
                </el-table-column>
                <el-table-column
                        label="模型大小"
                        prop="fileSize">
                </el-table-column>
                <el-table-column
                        :formatter="formatDate"
                        label="创建时间"
                        prop="createTime">
                    <!--<template slot-scope="scope">-->
                    <!--<i class="el-icon-time">{{formatTimeDate(scope.row.createTime)}}</i>-->
                    <!--</template>-->
                </el-table-column>
                <el-table-column
                        label="预览图"
                        prop="imageId">
                    <template slot-scope="scope">
                        <img :src="scope.row.imageId" @click="showImage(scope.row.imageId)" min-width="70" height="70"/>
                    </template>
                </el-table-column>
                <el-table-column
                        label="正视图"
                        prop="mainViewId">
                    <template slot-scope="scope">
                        <img :src="scope.row.mainViewId" @click="showImage(scope.row.mainViewId)" min-width="70"
                             height="70"/>
                    </template>
                </el-table-column>
                <el-table-column
                        label="俯视图"
                        prop="overViewId">
                    <template slot-scope="scope">
                        <img :src="scope.row.overViewId" @click="showImage(scope.row.overViewId)" min-width="70"
                             height="70"/>
                    </template>
                </el-table-column>
                <el-table-column
                        label="侧视图"
                        prop="sideViewId">
                    <template slot-scope="scope">
                        <img :src="scope.row.sideViewId" @click="showImage(scope.row.sideViewId)" min-width="70"
                             height="70"/>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑
                        </el-button>
                        <el-button type="text" icon="el-icon-delete" class="red"
                                   @click="handleDelete(scope.$index, scope.row)">删除
                        </el-button>
                        <br/>
                        <el-button type="text" class="gray" icon="el-icon-download"
                                   @click="downloadFile('stl',scope.row.id)">
                            下载模型
                        </el-button>
                        <el-button type="text" icon="el-icon-download" class="gray"
                                   @click="downloadFile('rar',scope.row.id)">
                            下载数据
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background @current-change="handleCurrentChange" layout="prev, pager, next"
                               :total="totalSize">
                </el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑模型信息" :visible.sync="editVisible" width="25%">
            <el-form ref="editFormData" :model="editFormData" :rules="editRules" label-width="80px">
                <el-form-item label="模型名称" prop="fileName">
                    <el-input v-model="editFormData.fileName"></el-input>
                </el-form-item>
                <el-form-item label="模型类型">
                    <el-select edit-select v-model="editFormData.type" placeholder="请选择模型类型">
                        <el-option v-for="(key,value) in typeMap" :label="key" :value="value"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit('editFormData')">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 图片查看弹出框 -->
        <el-dialog title="图片查看" :visible.sync="dialogImageShowVisible" width="30%">
            <img :src="imageUrl" width="100%"></img>
        </el-dialog>

        <!-- 删除提示框 -->
        <!--<el-dialog title="提示" :visible.sync="delVisible" width="300px" center>-->
        <!--<div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>-->
        <!--<span slot="footer" class="dialog-footer">-->
        <!--<el-button @click="delVisible = false">取 消</el-button>-->
        <!--<el-button type="primary" @click="deleteRow">确 定</el-button>-->
        <!--</span>-->
        <!--</el-dialog>-->

        <!--新增对话框-->
        <el-dialog title="添加模型" width="40%" :close-on-click-modal=false :visible.sync="dialogAddFormVisible">
            <el-form :label-position="'right'" label-width="30%" ref="addFormData" :model="addFormData" :rules="rules">
                <el-form-item label="模型类型" prop="type">
                    <el-select add-select v-model="addFormData.type">
                        <el-option v-for="(key,value) in typeMap" :label="key" :value="value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="选择模型文件" prop="stlFile">
                    <input type="file" accept=".stl" @change="handleFileChange($event, 'stlFile')">
                    <span>{{addFormFileSize.stlFile}}</span>
                </el-form-item>
                <el-form-item label="选择模型数据" prop="picRarFile">
                    <input type="file" accept=".zip,.rar" @change="handleFileChange($event, 'picRarFile')">
                    <span>{{addFormFileSize.picRarFile}}</span>
                </el-form-item>
                <el-form-item label="选择预览图" prop="imageFile">
                    <input type="file" accept=".jpg,.jpeg,.gif,.png" @change="handleFileChange($event, 'imageFile')">
                    <span>{{addFormFileSize.imageFile}}</span>
                </el-form-item>
                <el-form-item label="选择主视图" prop="mainViewImage">
                    <input type="file" accept=".jpg,.jpeg,.gif,.png"
                           @change="handleFileChange($event, 'mainViewImage')">
                    <span>{{addFormFileSize.mainViewImage}}</span>
                </el-form-item>
                <el-form-item label="选择侧视图" prop="sideViewImage">
                    <input type="file" accept=".jpg,.jpeg,.gif,.png"
                           @change="handleFileChange($event, 'sideViewImage')">
                    <span>{{addFormFileSize.sideViewImage}}</span>
                </el-form-item>
                <el-form-item label="选择俯视图" prop="overViewImage">
                    <input type="file" accept=".jpg,.jpeg,.gif,.png"
                           @change="handleFileChange($event, 'overViewImage')">
                    <span>{{addFormFileSize.overViewImage}}</span>
                </el-form-item>
                <el-form-item label="数据上传进度">
                    <el-progress :text-inside="true" :stroke-width="25" :percentage="uploadPercent"></el-progress>
                </el-form-item>

                <el-form-item style="text-align:center">
                    <el-button type="primary" @click="submitForm('addFormData')" class="yes-btn">确 定</el-button>
                    <el-button @click="resetForm('addFormData')">重 置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
    import DateUtil from "@/common/DateUtil"
    import HttpUtil from "@/common/HttpUtil"

    export default {
        name: 'modelTable',
        data() {
            return {
                idx: -1,//table中行索引
                imageUrl: '',
                uploadPercent: 0,//上传进度
                tableData: [], //表数据
                pageIndex: 1,//当前页
                totalSize: 0,//总条目数
                curPageSize: 10,//页面大小
                multipleSelection: [],//多选时选中数据数组
                select_cate: 'all',
                select_word: '',//查询关键字
                del_list: [],
                is_search: false,
                dialogAddFormVisible: false,//新增对话框开关
                editVisible: false, //编辑对话框开关
                delVisible: false,  //删除话框开关
                dialogImageShowVisible: false,
                editFormData: {//编辑数据
                    fileName: '',
                    type: '',
                },
                typeMap: {//模型类型显示转换
                    suggesting: '推荐',
                    culture_art: '文化艺术',
                    animal_plants: '动物植物',
                    life_education: '生活教育',
                    industrial_treatment: '工业医疗',
                    aeronautics_astronautics: '航空航天',
                    game_electronics: '游戏电子',
                    other: '其他'
                },
                addFormData: { //新增模型数据
                    type: 'suggesting', //模型类型
                    stlFile: null,//模型文件
                    picRarFile: null,//模型图片压缩文件
                    imageFile: null,//模型预览图
                    mainViewImage: null,//模型主视图
                    sideViewImage: null,//模侧视图
                    overViewImage: null//模型俯视图
                },
                addFormFileSize: { //新增模型文件大小信息
                    stlFile: "",
                    picRarFile: "",
                    imageFile: "",
                    mainViewImage: "",
                    sideViewImage: "",
                    overViewImage: ""
                },
                rules: {//新增模型数据校验规则
                    type: [{required: true, message: '请选择类型', trigger: 'blur'}],
                    stlFile: [{required: true, message: '请选模型文件', trigger: 'blur'}],
                    picRarFile: [{required: true, message: '请选数据文件', trigger: 'blur'}],
                    imageFile: [{required: true, message: '请选预览图', trigger: 'blur'}],
                    mainViewImage: [{required: true, message: '请选主视图', trigger: 'blur'}],
                    sideViewImage: [{required: true, message: '请选侧视图', trigger: 'blur'}],
                    overViewImage: [{required: true, message: '请选俯视图', trigger: 'blur'}]
                },
                editRules: {//编辑模型信息校验规则
                    fileName: [{required: true, message: '模型名称不能为空', trigger: 'blur'}]
                }

            }
        },
        created() {
            this.getData();
        },
        computed: {
            //过滤数据
            data() {
                return this.tableData.filter((d) => {
                    let is_del = false;
                    for (let i = 0; i < this.del_list.length; i++) {
                        if (d.id === this.del_list[i].id) {
                            is_del = true;
                            break;
                        }
                    }
                    if (!is_del) {
                        return d
                        // if (d.fileName.indexOf(this.select_word) > -1 ||
                        //     this.typeMap[d.type].indexOf(this.select_word) > -1) {
                        //     return d;
                        // }
                    }
                })
            }
        },
        methods: {
            // 分页导航
            handleCurrentChange(val) {
                this.pageIndex = val;
                this.getData();
            },
            // 获取 easy-mock 的模拟数据
            getData() {
                let self = this
                let pageSize = self.curPageSize
                this.$axios.get("/app/v1/model/list/" + self.pageIndex + "/" + pageSize, {
                    params: {'key': 'value'}
                }).then(function (response) {
                    self.tableData = response.data.pageInfos;
                    self.totalSize = response.data.pageCount * pageSize
                }).catch(function (error) {
                    self.$message.warning("请求模型列表数据失败")
                    // for (let i = 0; i < 10; i++) {
                    //     let tmpData = {
                    //         "id": "a24b467b-64bf-409d-9681-0e2669a4b481",
                    //         "userId": null,
                    //         "type": "suggesting",
                    //         "author": null,
                    //         "fileName": "Seahorse-pair.stl",
                    //         "fileSize": "4.78MB",
                    //         "imageId": "/image/08c380fdba8f488ab0ed4153274cf39e-image.png",
                    //         "mainViewId": "/image/08c380fdba8f488ab0ed4153274cf39e-main.png",
                    //         "sideViewId": "/image/08c380fdba8f488ab0ed4153274cf39e-side.png",
                    //         "overViewId": "/image/08c380fdba8f488ab0ed4153274cf39e-over.png",
                    //         "createTime": 1554341589000
                    //     }
                    //     tmpData.fileName = tmpData.fileName + i
                    //     self.tableData.push(tmpData)
                    // }
                });

            },
            search() {
                this.is_search = true;
                let self = this
                let pageSize = self.curPageSize
                this.$axios.get("/app/v1/model/list/" + self.pageIndex + "/" + pageSize, {
                    params: {'type': self.select_cate, 'fileName': self.select_word}
                }).then(function (response) {
                    self.tableData = response.data.pageInfos;
                    self.totalSize = response.data.pageCount * pageSize
                }).catch(function (error) {
                    self.$message.warning("请求模型列表数据失败")
                })
            },
            //时间格式化函数
            formatDate: DateUtil.formatDate,
            formatTimeDate: DateUtil.formatTimeDate,
            //类型转换函数
            formatType: function (row, column) {
                return this.typeMap[row.type]
            },
            filterTag(value, row) {
                return row.tag === value;
            },
            //编辑事件
            handleEdit(index, row) {
                this.idx = index;
                const item = this.tableData[index];
                this.editFormData.fileName = item.fileName
                this.editFormData.type = item.type
                this.editVisible = true;
            },
            //删除事件
            handleDelete(index, row) {
                let self = this
                this.idx = index;
                let id = this.tableData[index].id
                this.$confirm('删除不可恢复，是否确定删除?', '删除确认', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.post("/admin/model/delete-file/" + id).then(function (response) {
                        self.$message.success('删除成功')
                        self.freshTable(self.pageIndex)
                    }).catch(function (error) {
                        self.$message.error('删除失败');
                        HttpUtil.checkHttpErr(error)
                    })
                }).catch(() => {
                    //取消删除
                });
                //this.delVisible = true;
            },
            //删除所有事件
            delAll() {
                const length = this.multipleSelection.length;
                let str = '';
                this.del_list = this.del_list.concat(this.multipleSelection);
                for (let i = 0; i < length; i++) {
                    str += this.multipleSelection[i].fileName + ' ';
                }
                this.$message.error('删除了' + str);
                this.multipleSelection = [];
            },
            //批量删除选中事件
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 保存编辑
            saveEdit(formName) {
                let self = this
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        //this.$set(this.tableData, this.idx, this.form);
                        let row = this.tableData[this.idx]
                        let id = row.id
                        let fileName = this.editFormData.fileName
                        let type = this.editFormData.type

                        // Vue中axios踩坑之路-POST传参,https://blog.csdn.net/call_me_fly/article/details/79012581
                        // //方法一
                        // var qs = require('qs');
                        // axios.post('/foo', qs.stringify({ 'bar': 123 }));
                        // //方法二
                        // var params = new URLSearchParams();
                        // params.append('param1', 'value1');
                        // params.append('param2', 'value2');
                        // axios.post('/foo', params);

                        let params = new URLSearchParams();
                        params.append('id', id);
                        params.append('fileName', fileName);
                        params.append('type', type);

                        this.$axios.post("/admin/model/update", params).then(function (response) {
                            row.fileName = fileName
                            row.type = type
                            self.editVisible = false;
                            self.$message.success(`修改${row.fileName}成功`);
                        }).catch(function (error) {
                            self.$message.error(`修改${row.fileName}失败`);
                            HttpUtil.checkHttpErr(error)
                        })
                    } else {
                        //校验不通过
                    }
                });
            },
            // 确定删除
            // deleteRow() {
            //     let self = this
            //     debugger
            //     this.$axios.post("/admin/model/delete-file/" + self.tableData[self.idx].id).then(function (response) {
            //         //this.tableData.splice(this.idx, 1)
            //         self.freshTable(self.pageIndex)
            //         self.$message.success('删除成功')
            //         self.delVisible = false
            //     }).catch(function (error) {
            //         self.$message.error('删除失败');
            //     })
            // },
            //文件选择
            handleFileChange(event, type) {
                let file = event.target.files[0]
                this.addFormData[type] = file
                this.addFormFileSize[type] = DateUtil.getFileSize(file.size)
            },
            //新增提交
            submitForm(formName) {
                let self = this
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let config = HttpUtil.getMultiPostConfig(function (val) {
                            self.uploadPercent = val
                        })
                        let formData = new FormData();
                        for (let key in self.addFormData) {
                            formData.append(key, self.addFormData[key])
                        }
                        this.$axios.post("/admin/model/upload", formData, config).then(function (response) {
                            self.uploadPercent = 100;
                            self.freshTable(1)
                            self.$message.success('添加模型成功')
                        }).catch(function (error) {
                            self.$message.error('添加模型失败')
                            HttpUtil.checkHttpErr(error)
                        });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            //新增重置
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            //下载
            downloadFile(type, id) {
                if (type === "stl") {
                    location.href = "/app/v1/model/stl/" + id
                } else if (type === "rar") {
                    location.href = "/app/v1/model/rar/" + id
                }
            },
            //新增或sha
            freshTable(pageIndex) {
                this.pageIndex = pageIndex
                this.getData()
            },
            //显示图片对话框
            showImage(id) {
                this.imageUrl = id
                this.dialogImageShowVisible = true
            }
        }
    }

</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }

    .del-dialog-cnt {
        font-size: 16px;
        text-align: center
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .gray {
        color: lightgray;
    }

    .mr10 {
        margin-right: 10px;
    }

    input[type='file'] {
        padding: 5px;
        background-color: gainsboro;
        border-radius: 5px;
        width: 70%;
    }

    .el-progress, .el-select[add-select] {
        width: 72%;
    }

    .el-select[edit-select] {
        width: 100%;
    }
</style>
